﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace Utility.NodeGraphs
{
	public class NodeGraph : ScriptableObject
	{
		public List<Node> nodes = new List<Node> ();
		public Vector2 position = default;
		public float scale = 1;

		public virtual float MinScale => 0.3f;
		public virtual float MaxScale => 1;

		private void Awake ()
		{
			OnCreate ();
		}

		public Node GetNode (int index)
		{
			if (index < 0 || index >= nodes.Count)
			{
				return null;
			}
			return nodes[index];
		}

		public virtual void OnCreate () { }

		public virtual TNode AddNewNode<TNode> (string name = null)
			where TNode : Node
		{
			TNode node = CreateInstance<TNode> ();
			node.name = string.IsNullOrEmpty (name) ? node.GetType ().Name : name;
			AddNode (node);
			return node;
		}

		public virtual bool AddNode (Node node)
		{
			if (nodes.Contains (node))
			{
				return false;
			}

			node.graph = this;
			nodes.Add (node);
			if (!string.IsNullOrEmpty (AssetDatabase.GetAssetPath (this)))
			{
				AssetDatabase.AddObjectToAsset (node, this);
				AssetTools.AssetDatabaseEX.ReimportAsset (this);
			}
			return node;
		}

		public virtual void RemoveNode (Node node)
		{
			if (nodes.Contains (node))
			{
				node.OnRemove ();
				nodes.Remove (node);
				DestroyImmediate (node, true);
				AssetTools.AssetDatabaseEX.ReimportAsset (this);
			}
		}

		public virtual void Clear ()
		{
			if (!string.IsNullOrEmpty (AssetDatabase.GetAssetPath (this)))
			{
				foreach (var node in nodes)
				{
					DestroyImmediate (node, true);
				}
				nodes.Clear ();
				AssetTools.AssetDatabaseEX.ReimportAsset (this);
			}
		}


	}
}